package com.qls.ali.biz.service.fz.impl;


import com.qls.ali.biz.data.util.FzUtil;
import com.qls.ali.biz.service.fz.Cache;
import com.qls.ali.biz.service.fz.RpService;
import com.qls.ali.biz.service.mybatis.HtSellRoomService;
import com.qls.ali.biz.service.mybatis.OpOurRateplanService;
import com.qls.ali.model.vo.OpOurRateplanVo;
import com.qls.core.constant.Constant;
import com.qls.core.entity.HtSellRoom;
import com.qls.core.entity.OpOurRateplan;
import com.qls.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author yunchao
 */
@Slf4j
@Service
public class RpServiceImpl implements RpService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OpOurRateplanService opOurRateplanService;

    @Autowired
    private HtSellRoomService htSellRoomService;

    @Autowired
    private Cache cache;


    @Override
    public Map<String, List<Integer>> pushBatch(List<HtSellRoom> htLogicRooms, Integer storeId, String appKey, String secret, String session, List<OpOurRateplanVo> opOurRateplans, Integer partnerId) {
        String infix = "qls";
        String ok = "xhotel_rateplan_update_response";
        Map<String, List<Integer>> rpCrpIdsMap = new HashMap<>();
        for (HtSellRoom htLogicRoom : htLogicRooms) {
            Long rpCode = htLogicRoom.getRpCode();
            List<Integer> crpIds = new ArrayList<>();
            for (OpOurRateplan opOurRateplan : opOurRateplans) {
                Integer id = opOurRateplan.getId();
                htLogicRoom.setBreakfastCal(null);
                htLogicRoom.setCancelPolicyCal(null);
                // 自定义早餐
                Integer breakfastNum = opOurRateplan.getBreakfastNum();
                if (!breakfastNum.equals(-1)) {
                    htLogicRoom.setBreakfastNum(breakfastNum);
                }
                // 推送渠道
                String channel = opOurRateplan.getChannel();
                // 自定义退改政策
                String cancel = opOurRateplan.getCancleJsonStr();
                if (!"NONE".equals(cancel)) {
                    htLogicRoom.setCancelPolicy(cancel);
                }
                // 自定义价格政策编码
                String newRpCode = htLogicRoom.getRpCode() + infix + id;
                String result = FzUtil.pushRp(htLogicRoom, newRpCode, appKey, session, secret, channel);
                if (!result.contains(ok)) {
                    log.warn("{}：rp推送失败，失败原因：{}", rpCode, result);
                    continue;
                }
                crpIds.add(id);
            }
            if (!crpIds.isEmpty()) {
                rpCrpIdsMap.put(rpCode + "_" + htLogicRoom.getRoomCode(), crpIds);
            }
        }
        // 更新rp缓存
        if (!rpCrpIdsMap.isEmpty()) {
            this.saveRpCache(storeId, rpCrpIdsMap, partnerId);
        }
        return rpCrpIdsMap;
    }

    @Override
    public boolean del(Long rpCode, List<Integer> crpIds, Integer storeId, String appKey, String secret, String session) {
        String ok = "xhotel_rateplan_delete_response";
        String key = rpCode.toString();
        // 查询缓存的自定义价格政策id
        Map<String, Object> rpStoreCache = cache.getRpStoreMap(key, storeId);
        if (rpStoreCache.isEmpty()) {
            return true;
        }
        List<Integer> crpIdsCache = (List<Integer>) rpStoreCache.get("crpIds");
        if (Objects.isNull(crpIdsCache)) {
            return true;
        }
        List<Integer> delCrpIds;
        // 如果为空集合 说明自定义价格政策全部删除  不为空只删除集合内的自定义价格政策
        if (Objects.isNull(crpIds)) {
            delCrpIds = crpIdsCache;
        } else {
            delCrpIds = crpIds;
        }
        int count = delCrpIds.size();
        // 删除成功的自定义rpId集合
        List<Integer> deledCrpIds = new ArrayList<>();
        for (Integer crpId : delCrpIds) {
            String newRpCode = key + "qls" + crpId;
            String result = FzUtil.delRp(newRpCode, appKey, session, secret);
            if (!result.contains(ok)) {
                log.warn("店铺id：{}，rp：{}，删除失败，失败原因：{}", storeId, newRpCode, result);
                continue;
            }
            deledCrpIds.add(crpId);
        }
        if (deledCrpIds.isEmpty()) {
            return false;
        }
        // 删除店铺缓存rp
        boolean flag = cache.delRpStoreMap(key, storeId, deledCrpIds);
        if (!flag) {
            return false;
        }
        // 根据id更新自定义rp的数量
        for (Integer id : deledCrpIds) {
            opOurRateplanService.addCountById(-1, id);
        }
        return deledCrpIds.size() == count;
    }

    @Override
    public void push(Long rpCode, List<Integer> crpIds, Integer storeId, String appKey, String secret, String session, Integer partnerId) {

        if (!redisUtil.hashExistFiled(Constant.Redis.GOODS_BL_CRP_HTL_ROOM_RP_STORE.getValue() + "_" + storeId, rpCode.toString())) {
            return;
        }
        HtSellRoom htLogicRoom = htSellRoomService.getById(rpCode);
        List<HtSellRoom> htLogicRooms = new ArrayList<>();
        htLogicRooms.add(htLogicRoom);
        List<OpOurRateplanVo> opOurRateplans = opOurRateplanService.getRatePlanPrice(storeId, htLogicRoom.getHotelCode());
        this.pushBatch(htLogicRooms, storeId, appKey, secret, session, opOurRateplans, partnerId);
    }

    /**
     * rp缓存
     *
     * @param storeId 店铺id
     * @param map     Map<String, List<Integer>>
     */
    private void saveRpCache(Integer storeId, Map<String, List<Integer>> map, Integer partnerId) {
        for (String v : map.keySet()) {
            String[] newStr = v.split("_");
            String rpCode = newStr[0];
            String roomCode = newStr[1];
            List<Integer> crpIds = map.get(v);
            List<Integer> newCrpIds = cache.addRpStoreMap(roomCode, rpCode, storeId, crpIds, partnerId);
            if (newCrpIds.isEmpty()) {
                return;
            }
            for (Integer id : newCrpIds) {
                opOurRateplanService.addCountById(1, id);
            }
        }
    }
}
